<?php
namespace app\api\controller\signreport;

use app\api\controller\Baseuser;
use app\common\model\signreport\Report as reportModel;
use think\facade\Request;

class Report extends Baseuser
{
    // 查询日报列表
    public function getReportList()
    {
        $ReportType =  Request::instance()->param('ReportType');
        // 获取用户信息
        $where['UId'] = $this->user_id;
        $where['ReportType'] = $ReportType;
        $data = (new reportModel())->getReportList($where);
        return myok($data);
    }
    // 查询日报内容
    public function getReport()
    {
        $Id =  Request::instance()->param('Id');
        $data = (new reportModel())->getReport($Id);
        return myok($data);
    }

    // 写日报
    public function addReport()
    {
        $params =  Request::instance()->param();

        // 获取用户信息
        $params['UId'] = $this->user_id;
        $time = Date('Y-m-d', time());
        $params['ReportTime'] = strtotime($time);
        $result = $this->validate($params, 'Report');
        if(true !== $result){
            return myerr($result);
        }
        // 判断是否已经添加
        $res = $this->isCheck($params['ReportType'], $time, $this->user_id);
        if ($res == 0) {
            // 将内容插入
            $res = (new reportModel())->addReport($params);
            if ($res) {
                return myok('添加成功');
            } else {
                return myerr($res);
            }
        } else {
            return myerr('已经提交');
        }
    }

    // 更新日报
    public function editReport()
    {
        $params =  Request::instance()->param();


        $result = $this->validate($params, 'Report.edit');
        if(true !== $result){
            return myerr($result);
        }
        // 将内容插入
        $res = (new reportModel())->editReport($params);
        if ($res) {
            return myok('更新成功');
        } else {
            return myerr($res);
        }
    }

    // 判断是否可以添加
    private function isCheck($ReportType, $time, $user_id)
    {
        $count = 0;
        $reportModel = new reportModel();
        switch($ReportType) {
            case 1:
                $count = $reportModel->where('ReportTime', strtotime($time))
                    ->where('UId', $user_id)->where('ReportType', $ReportType)->count();
                break;
            case 2:
                $times = getWeek($time);
                $count = $reportModel->where('ReportTime', '>=', $times[0])
                    ->where('ReportTime', '<', $times[1])
                    ->where('UId', $user_id)->where('ReportType', $ReportType)->count();
                break;
            case 3:
                $times = getMonth($time);
                $count = $reportModel->where('ReportTime', '>=', $times[0])
                    ->where('ReportTime', '<', $times[1])
                    ->where('UId', $user_id)->where('ReportType', $ReportType)->count();
                break;
        }
        return $count;
    }
}
